<template>
  <div class="scroll-container">
    <h2>{{ title }}</h2>
    <a-divider
      type="horizontal"
      :style="{ borderColor: '#19a7ff', borderWidth: '2px' }"
    />
    <a-spin :spinning="loading">
      <a-row :gutter="20">
        <a-col
          v-for="(image, index) in Data"
          :key="index"
          :span="6"
        >
          <div class="image-container">
            <a-image
              :src="image.imgUrl"
              :alt="image.name"
              :preview="false"
              @click="handleClickPic(image)"
              @error="handleImageError(image)"
            />
            <div v-if="image.loadError" class="error-overlay">
              图片加载失败
            </div>
          </div>
        </a-col>
      </a-row>
      <a-empty v-if="!loading && Data.length === 0" description="暂无图片数据" />
    </a-spin>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import axiosInstance from "@/axios/axios.js";
import { message } from 'ant-design-vue';

export default defineComponent({
  name: 'ChainDataImage',
  data() {
    return {
      loading: false,
      Data: [],
      title: '数据详情',
    };
  },
  async created() {
    // 检查登录状态
    if (!this.$cookies.get('jwt') || !sessionStorage.getItem("isLogin")) {
      message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 检查路由参数
    const requiredParams = [
      'experiment_id',
      'grantorName',
      'experiment_set_name',
      'experiment_batch_name',
      'experiment_name'
    ];
    
    const missingParams = requiredParams.filter(param => !this.$route.query[param]);
    if (missingParams.length > 0) {
      message.error('缺少必要的参数');
      this.$router.push('/ChainData');
      return;
    }

    // 检查用户信息
    const username = this.$cookies.get("username");
    
    if (!username) {
      message.error('用户信息不完整，请重新登录');
      this.$router.push('/login');
      return;
    }

    // 设置标题
    this.title = `数据详情: ${this.$route.query.experiment_name}`;

    this.loading = true;
    try {
      const response = await axiosInstance({
        method: "POST",
        url: "/data/getImagesOnChain",
        headers: {
          Authorization: `Bearer ${this.$cookies.get("jwt")}`
        },
        data: {
          username,
          grantorName: this.$route.query.grantorName,
          dataId: this.$route.query.experiment_id,
          experimentSetName: this.$route.query.experiment_set_name,
          batchName: this.$route.query.experiment_batch_name,
          experimentName: this.$route.query.experiment_name,
        },
      });

      if (response.data?.data?.images && response.data.data.url) {
        const imagesPath = response.data.data.url;
        this.Data = response.data.data.images.map(item => ({
          ...item,
          imgUrl: imagesPath + item.name,
          loadError: false
        }));
        console.log("Loaded images:", this.Data);
      } else {
        console.warn("No images data in response:", response.data);
        this.Data = [];
      }
    } catch (error) {
      console.error('获取图片数据失败:', error);
      if (error.response?.status === 401) {
        message.error('登录已过期，请重新登录');
        this.$router.push('/login');
      } else if (error.response?.status === 403) {
        message.error('没有访问权限');
        this.$router.push('/ChainData');
      } else {
        message.error(`获取数据失败: ${error.response?.data?.message || error.message}`);
      }
    } finally {
      this.loading = false;
    }
  },
  methods: {
    handleClickPic(image) {
      if (image.loadError) {
        message.error('图片加载失败，无法查看详情');
        return;
      }

      if (!image.experiment_set_id || !image.batch_id || !image.experiment_id || !image.tx_hash) {
        message.error('图片信息不完整');
        return;
      }

      this.$router.push({
        path: '/detail',
        query: {
          imgUrl: image.imgUrl,
          experimentSetId: image.experiment_set_id,
          batchId: image.batch_id,
          experimentId: image.experiment_id,
          hash: image.tx_hash,
        }
      });
    },
    handleImageError(image) {
      // 标记图片加载失败
      const index = this.Data.findIndex(item => item.image_id === image.image_id);
      if (index !== -1) {
        this.Data[index].loadError = true;
      }
    }
  }
});
</script>

<style scoped>
.scroll-container {
  max-width: 1200px;
  margin: auto;
  padding: 20px;
  max-height: 650px;
  overflow-y: auto;
}

.image-container {
  position: relative;
  max-width: 100%;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
  cursor: pointer;
}

.image-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.image-container .a-image {
  max-width: 100%;
  max-height: 200px;
  display: block;
  margin: auto;
  object-fit: contain;
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.1);
  color: #ff4d4f;
  font-size: 14px;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .image-container .a-image {
    max-height: 150px;
  }
}

@media (max-width: 480px) {
  .image-container .a-image {
    max-height: 100px;
  }
}
</style>